package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 工单查询API
 */

public class apiGetWOList implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetWOList.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        JSONObject signJson = signUtil.CheckSign(JSONObject.parseObject(callJson, Feature.OrderedField));
        log.info("[签名验证结果]:");
        log.info(signJson);
        if (signJson != null && 1==2) {
            return signJson.toString();
        } else {
            try {
                //解析Json
                JSONObject inJson = JSONObject.parseObject(callJson, Feature.OrderedField);

                //获取查询参数
                String c_user_id = inJson.getString("c_user_id");
                String c_user_type = inJson.getString("c_user_type");
                String s_query_type = inJson.getJSONObject("data").getString("s_query_type");// 查询类型 upcoming待办 history历史处理  involve我的关注
                String s_query_info = inJson.getJSONObject("data").getString("s_query_info"); // 模糊查询项
                String s_workorder_id = inJson.getJSONObject("data").getString("s_workorder_id");// 输入的工单ID
                String s_customer_name = inJson.getJSONObject("data").getString("s_customer_name"); // 客户姓名
                String s_customer_mobile = inJson.getJSONObject("data").getString("s_customer_mobile");// 手机
                String s_workorder_status = inJson.getJSONObject("data").getString("s_workorder_status"); // 工单状态

                log.debug("请求参数-操作人信息-c_user_id:" + c_user_id);
                log.debug("请求参数-查询条件-s_query_type:" + s_query_type + " s_query_info:" + s_query_info + " s_workorder_id:" + s_workorder_id + " s_customer_name:" + s_customer_name + " s_customer_mobile:" + s_customer_mobile + " s_workorder_status:" + s_workorder_status);

                // 查询判断当前这个操作人是客户还是员工
                // 客户信息
                String Customer_Guid = null;
                String Loginname = null;
                String role_id = null;

                // 员工信息
                String Rolegroup_Id = null;
                String Staff_Id = null;
                List selectResult = eliteBean.chaxun_sql("Select R2.Rolegroup_Id, R1.Staff_Id, R2.Rolegroupdescription, R1.Staffname, sr.Role_id" +
                        "  From Staff R1" +
                        "  Left Join Rolegroup R2" +
                        "    On R1.Defaultrolegroup = R2.Rolegroup_Id" +
                        "  Left Join staffrole sr" +
                        "    On R1.staff_id = sr.staff_id" +
                        " Where R1.Workstatus = 'ONLINE'" +
                        "   And R1.Staff_Id = '" + c_user_id + "' Limit 1", "dataSource");

                if (selectResult.size() <= 0) {
                    List selectResultc = eliteBean.chaxun_sql("Select Customer_Guid, Customername, Mobile, Loginname From Customer Where Customer_Guid = '" + c_user_id + "' Limit 1", "dataSource");
                    if (selectResultc.size() <= 0) {

                        result.put("code", 1007);
                        result.put("msg", "当前操作人非法！");
                        return result;

                    } else {
                        Map selectResultcm = selectResultc.get(0);
                        Customer_Guid = selectResultcm.get("Customer_Guid");
                        Loginname = selectResultcm.get("Loginname");
                        String Customername = selectResultcm.get("Customername");
                        String Mobile = selectResultcm.get("Mobile");
                        log.debug("当前操作客户信息-Customer_Guid:" + Customer_Guid + " Customername:" + Customername + " Mobile:" + Mobile + " Loginname:" + Loginname);
                        c_user_type = "customer";

                    }
                } else {
                    Map selectResultm = selectResult.get(0);
                    Rolegroup_Id = selectResultm.get("Rolegroup_Id");
                    Staff_Id = selectResultm.get("Staff_Id");
                    String Rolegroupdescription = selectResultm.get("Rolegroupdescription");
                    String Staffname = selectResultm.get("Staffname");
                    role_id=selectResultm.get("Role_id");
                    log.debug("当前操作员工信息-Rolegroup_Id:" + Rolegroup_Id + " Rolegroupdescription:" + Rolegroupdescription + " Staff_Id:" + Staff_Id + " Staffname:" + Staffname);
                    c_user_type = "staff";

                }


                String q_WhereSQL = " Where 1=1 ";
                log.debug("初始化控制查询条件SQL:" + q_WhereSQL);

                // 模糊查询条件处理
                if (!KHUtil.isNull(s_query_info)) {
                    q_WhereSQL = q_WhereSQL + " And (Cus.Customername = '" + s_query_info + "' Or Cus.Mobile = '" + s_query_info + "' Or Obj.Workorderid = '" + s_query_info + "')";
                }

                if (!KHUtil.isNull(s_workorder_id)) {
                    q_WhereSQL = q_WhereSQL + " And Obj.Workorderid = '" + s_workorder_id + "'";
                }
                if (!KHUtil.isNull(s_customer_name)) {
                    q_WhereSQL = q_WhereSQL + " And Cus.Customername = '" + s_customer_name + "'";
                }
                if (!KHUtil.isNull(s_customer_mobile)) {
                    q_WhereSQL = q_WhereSQL + " And Cus.Mobile = '" + s_customer_mobile + "'";
                }
                if (!KHUtil.isNull(s_workorder_status)) {
                    q_WhereSQL = q_WhereSQL + " And Obj.Objectivestatus = '" + s_workorder_status + "'";
                }

                // 根据操作人员类型控制查询权限
                if (c_user_type == "customer" && Loginname == null) {
                    q_WhereSQL = q_WhereSQL + " And Obj.Customer_Guid = '" + Customer_Guid + "'";
                } else if (c_user_type == "customer") {
                    q_WhereSQL = q_WhereSQL + " And (Obj.Customer_Guid = '" + Customer_Guid + "' Or Eta.Handleby_Id = '" + Loginname + "')";
                }

                // 根据查询类型控制查询范围s_query_type");// 查询类型 // 查询类型 upcoming待办 history历史处理  involve我的关注
                if (s_query_type == "upcoming") {
                    q_WhereSQL = q_WhereSQL + " And (Eta.HandleBy_ID='" + Staff_Id + "' OR (Eta.HANDLEGROUP_ID='" + Rolegroup_Id + "' and Eta.CUR_ROLEID='"+ role_id +"'  and (Eta.handleby_id is null or Eta.handleby_id='')))  ";
                } else if (s_query_type == "involve") {
                    q_WhereSQL = q_WhereSQL + " And Obj.map_id in(select distinct map_id from wo3_nodemap_extend  where extendid='CURRENTGROUP' and extendvalue='" + Rolegroup_Id + "')"; // 我的关注
                } else if(s_query_type == "history") {
                    q_WhereSQL = q_WhereSQL + " AND WS.OLDHANDLEBY_ID='" + Staff_Id + "' and (Obj.objectivestatus = 'OPEN' or Obj.objectivestatus='CLOSE' or Obj.objectivestatus='FAIL') and  WS.HANDLEBY_ID != '"+ Staff_Id +"' " ;
                }
                q_WhereSQL = q_WhereSQL + "order by  Obj.workorderid desc Limit 100 ";

                String queryWorkOrderSQL="";
                if(s_query_type == "upcoming"||s_query_type == "involve"){
                log.debug("控制查询条件完成SQL:" + q_WhereSQL);
                 queryWorkOrderSQL ="Select Distinct Obj.Workorderid As workorder_id,\n" +
                        "Obj.Objective_Guid As objective_guid,\n" +
                        "Eta.Elitetask_Guid As elitetask_guid,\n" +
                        "Fm.Mapname As map_name,\n" +
                        "Nm.Nodemapname As node_name,\n" +
                        "Cus.Customername As customer_name,\n" +
                        "Cus.Mobile As mobile,\n" +
                        "Date_Format(Eta.Expectstarttime, '%Y-%m-%d %H:%i:%S') As expect_starttime,\n" +
                        "Date_Format(Eta.Expectendtime, '%Y-%m-%d %H:%i:%S') As expect_endtime,\n" +
                        "Priy.Prioritydescription As priority,\n" +
                        "R1.Rolegroupdescription As rolegroup_name,\n" +
                        "S1.Staffname As staff_name,\n" +
                        "Eta.Comments As comments,so.OBJECTIVESTATUSDESCRIPTION as objectivestatus\n" +
                        " FROM objective Obj\n" +
                        " left join ELITETASK Eta  on Eta.objective_guid=Obj.objective_guid\n" +
                        " left join WO3_FRAME_MAP fm on fm.map_id=Obj.map_id\n" +
                        " left  join WO3_node_MAP nm on Eta.curstep_id_map=nm.nodemap_id and nm.MAP_ID=fm.map_id\n" +
                        " LEFT JOIN Customer  Cus ON Obj.Customer_GUID = Cus.Customer_GUID\n" +
                        " Left Join sysc_priority Priy On Eta.Priority=Priy.Priority_ID \n" +
                        "LEFT JOIN ROLEGROUP R1 ON R1.ROLEGROUP_ID=Eta.HandleGroup_ID\n" +
                        "LEFT JOIN STAFF S1 ON S1.STAFF_ID=Eta.HandleBy_ID\n" +
                        "LEFT JOIN STAFF S2 ON S2.STAFF_ID=Eta.ModifiedBy\n" +
                        "LEFT JOIN STAFFROLEGROUP SR ON SR.STAFF_ID=S1.STAFF_ID\n" +
                        "left join role role on Eta.handlerole_id=role.role_id \n" +
                        "LEFT JOIN sysc_objectivestatus so ON Obj.objectivestatus = so.objectivestatus\n" +
                        "left join tabcwo_business_info tw on Obj.OBJECTIVE_GUID=tw.RELATION_ID"+ q_WhereSQL;
                }else if(s_query_type == "history"){
                    log.debug("控制历史处理查询条件完成SQL:" + q_WhereSQL);
                     queryWorkOrderSQL ="Select Distinct Obj.Workorderid As workorder_id,\n" +
                             "Obj.Objective_Guid As objective_guid,\n" +
                            " Eta.elitetask_guid As elitetask_guid,\n" +
                            " fm.mapname As map_name,\n" +
                            " nm.nodemapname As node_name,\n" +
                            " Cus.Customername As customer_name,\n" +
                            " Cus.Mobile As mobile,\n" +
                            " Date_Format(Eta.Expectstarttime, '%Y-%m-%d %H:%i:%S') As expect_starttime,\n" +
                            " Date_Format(Eta.Expectendtime, '%Y-%m-%d %H:%i:%S') As expect_endtime,\n" +
                            " Priy.Prioritydescription As priority,\n" +
                            " R1.Rolegroupdescription As rolegroup_name,\n" +
                            " S1.Staffname As staff_name,\n" +
                            " Eta.Comments As comments,\n" +
                            " if(so.OBJECTIVESTATUS='OPEN','已办理未结案',so.OBJECTIVESTATUSDESCRIPTION) as objectivestatus\n" +
                            "FROM WORKORDERSTEP3 WS \n" +
                            "LEFT JOIN objective Obj ON Obj.objective_guid=wS.workorder_guid\n" +
                            "left join ELITETASK Eta on Eta.objective_guid=Obj.objective_guid\n" +
                            "left join WO3_FRAME_MAP fm on fm.map_id=Obj.map_id\n" +
                            "left  join WO3_node_MAP nm on Eta.curstep_id_map=nm.nodemap_id and nm.MAP_ID=fm.map_id\n" +
                            "LEFT JOIN Customer  Cus ON Obj.Customer_GUID = Cus.Customer_GUID\n" +
                            "Left Join sysc_priority Priy On Eta.Priority=Priy.Priority_ID \n" +
                            "LEFT JOIN ROLEGROUP R1 ON R1.ROLEGROUP_ID=Eta.HandleGroup_ID\n" +
                            "LEFT JOIN STAFF S1 ON S1.STAFF_ID=Eta.HandleBy_ID\n" +
                            "LEFT JOIN STAFF S2 ON S2.STAFF_ID=Eta.ModifiedBy\n" +
                            "left join role role on Eta.CUR_ROLEID=role.role_id \n" +
                            "LEFT JOIN sysc_objectivestatus so ON Obj.objectivestatus = so.objectivestatus\n" + q_WhereSQL;

                }

                log.debug("执行工单查询数据SQL:" + queryWorkOrderSQL);

                List WorkOrderList = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");
                //获取总行数
                log.debug("执行工单查询数据SQL获取总条数:" + WorkOrderList.size());

                String reJoson = Util.getJsonFromList(WorkOrderList);
                reJoson=!KHUtil.isNull(reJoson)?reJoson:"[]";
                long endTime = System.currentTimeMillis();
                result.put("code", 1);
                result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));
                JSONArray dataArr = JSONArray.parseArray(reJoson);
                result.put("data", dataArr);

            } catch (Exception e) {
                result.put("code", 1008);
                result.put("msg", e.getMessage());
            }

        }

        return result.toString();
    }
}